package inet.app.view.activity;

import inet.app.R;
import inet.app.common.XoSoConstants;
import inet.app.controller.connect.JsonParser;
import inet.app.controller.database.DBConfig;
import inet.app.controller.database.DatabaseManager;
import inet.app.controller.parser.Parser_Somo;
import inet.app.model.object.Somo_Item;
import inet.app.model.util.ProgressDialog;
import inet.app.model.util.SmartLog;
import inet.app.model.util.Util;
import inet.app.view.adapter.SomoAdapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/*public class SomoActivity extends BaseActivity*/
public class SomoActivity extends BaseFragmentActivity {

	private ListView listview;
	private TextView tvfotter, tvTitle;
	private EditText etinput;
	private SomoAdapter adapter;
	private List<Somo_Item> arraylist_sm = new ArrayList<Somo_Item>();
	private Parser_Somo parser = new Parser_Somo();
	private boolean isExistData;
	private AsyncTask<Void, Void, Void> mInsertDataTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.somo);
		pdia = new ProgressDialog(SomoActivity.this);
		initBase();
		setup();
		Load_data();
	}

	private void setup() {

		listview = (ListView) findViewById(R.id.listViewSomo);
		etinput = (EditText) findViewById(R.id.edtSomoSearch);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvTitle.setText("Giải Mã Giấc Mơ");
		// set method text changed
		etinput.addTextChangedListener(mTextWatcher);
		// Load animation
		tvfotter = (TextView) findViewById(R.id.tvfotter);
		final Animation text_animation = AnimationUtils.loadAnimation(this,
				R.anim.custom_text_animation);
		tvfotter.startAnimation(text_animation);
		tvfotter.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				pdia.show();
				Intent myWebLink = new Intent(
						android.content.Intent.ACTION_VIEW);
				myWebLink.setData(Uri.parse("http://m.ole.vn/"));
				pdia.dismiss();
				startActivity(myWebLink);
			}
		});

	}

	private void Load_data() {
		pdia.show();
		isExistData = DatabaseManager.instance(this).getDaoSomo()
				.isExistData(DBConfig.TABLE_SOMO);
		boolean isLoadSomoFromDb = Util.getPreferences(
				XoSoConstants.GET_SOMO_FROM_DB, this);
		if (isExistData) {

			SmartLog.d("load somo from db");
			arraylist_sm = mDbManager.getDaoSomo().selectAll();
			adapter = new SomoAdapter(this, arraylist_sm);
			listview.setAdapter(adapter);
			pdia.dismiss();
		}

		if (!isLoadSomoFromDb) {

			SmartLog.d("load somo from server");
			Util.savePreferences(XoSoConstants.GET_SOMO_FROM_DB, true, this);
			thread_somo.start();
		}
	}

	private TextWatcher mTextWatcher = new TextWatcher() {
		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			adapter.getFilter().filter(s);
			adapter.notifyDataSetChanged();
		}
	};

	public void onResume() {

		if (((MyApp) getApplication()).isKill()) {
			finish();
		} else {
			((MyApp) getApplication()).setRunning(true);
		}
		super.onResume();
	}

	/**
	 * load so mo from server
	 */
	private Thread thread_somo = new Thread() {

		public void run() {
			JsonParser jParser = new JsonParser();
			String jobject = jParser.getURL(request.getsomo());
			if (jobject != null) {
				Message msg = handler_somo.obtainMessage(0, jobject);
				handler_somo.sendMessage(msg);
			} else {
				Message msg = handler_somo.obtainMessage(1);
				handler_somo.sendMessage(msg);
			}

		}
	};

	/**
	 * fill data to view
	 */
	private Handler handler_somo = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0) {
				String json = (String) msg.obj;
				arraylist_sm = parser.getListSomo(json);

				// add somo to db
				if (arraylist_sm != null && arraylist_sm.size() != 0) {

					Toast.makeText(SomoActivity.this,
							"Cập nhật sổ mơ thành công", Toast.LENGTH_SHORT)
							.show();
					adapter = new SomoAdapter(SomoActivity.this, arraylist_sm);
					listview.setAdapter(adapter);

					// continue search
					String search = etinput.getText().toString();
					if (!TextUtils.isEmpty(search)) {
						adapter.getFilter().filter(search);
						adapter.notifyDataSetChanged();
					}

					// insert somo to database
					mInsertDataTask = new AsyncTask<Void, Void, Void>() {
						@Override
						protected Void doInBackground(Void... params) {
							mDbManager.getDaoSomo().deleteAll();
							long result = mDbManager.getDaoSomo()
									.insertCollection(arraylist_sm);
							if (result == -1) {
								SmartLog.e("insert list somo to db failed");
							}
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {
							mInsertDataTask = null;
						}

					};

					mInsertDataTask.execute();
				}

				pdia.dismiss();
			} else if (msg.what == 1) {
				pdia.dismiss();
				if (!isExistData) {
					Util.showDialog(1, SomoActivity.this);
				} else {
					Load_data();
				}
			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showQuitDialog(this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onStop() {
		super.onStop();

		handler_somo.removeCallbacksAndMessages(null);

		// stop insert database
		if (mInsertDataTask != null) {
			mInsertDataTask.cancel(true);
			mInsertDataTask = null;
			// delete tempt db
			mDbManager.getDaoSomo().deleteAll();
		}

		// stop load somo
		if (thread_somo != null && thread_somo.isAlive()) {
			thread_somo.interrupt();
			thread_somo = null;
		}
	}

}
